package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
@Log4j2
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (!StringUtils.isEmpty(dto.getPassword()) && !StringUtils.isEmpty(dto.getPhone())){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser != null){
                String password = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
                if (password.equals(apUser.getPassword())){
                    Map<String , Object> map = new HashMap<>();
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("token" , AppJwtUtil.getToken(apUser.getId().longValue()));
                    map.put("user" , apUser);
                    return ResponseResult.okResult(map);
                }else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "密码错误，请重试");
                }
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST , "用户名不存在");
            }
        }else {
            if (dto.getEquipmentId() == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            Map<String , Object> map = new HashMap<>();
            map.put("token" , 1l);
            return ResponseResult.okResult(map);
        }
    }
}
